<?php

class Kit_Controller extends WakEngineController {

    function _setUp() {
        $id=$this->response->shiftNode();
        $this->response->id=$id;
        // getting kit
		try {
            // loading kit cfg
            $this->response->cfg=Webappkit::getCfgFromId($id);
            // listing subkits
            $subkits=Webappkit::listKits(Webappkit::getPathFromId($id));
            $this->response->subkits=$subkits;
            /*foreach ($subkits as $subkit) {
                $subid=$id.'.'.$subkit;
                $this->response->subkits[$subid]=$cfg;
            }*/
            // trying to load kit
			if (!$this->kit=Webappkit::getKit($id)) {
				throw new WakEngineErrorPage("kit not found",404);
			}

			$this->response->kit=$this->kit;
		} catch (WakBadKit $e) {
			// re-routing to badkit page
			$this->_setAction('badkit');
			$this->response->error=$e;
		} catch (WakBadCfg $e) {
			$this->_setAction('badkit');
			$this->response->error=$e;
        } catch (WakMissingKit $e) {
            $this->response->error=$e;
            // $this->_setAction('missingkit');
        } catch (WakBadPhp $e) {
            $this->response->error=$e;
            // $this->_setAction('badphp');
        } catch (WakMissingFile $e) {
            $this->_setAction('badkit');
            $this->response->error=$e;
        }

    }

    /**
     * kit home/index
     */
    function index() {
		// echo "kit index";
		try {
			$kit=&$this->kit;
			// $this->response->subkits=$this->cfg; //print_r($this->subkits);
			// does the kit provide unit tests ?
            if ($kit and $tests=$kit->getTools('SimpleTestTool')) {
                //$this->response->tests=$tests;
                // print_r($tests);
                $this->response->tests=$tests['tests']->run();
                /*foreach ($tests as $tool) {
                    $this->response->tests_reports[]=$tool->run();
                }*/
            }
			// is there some doc ?
			/*if (is_file($kit->getpath().'docs/index.rest.txt')) {
				$txt=join('',file($kit->getpath().'docs/index.rest.txt')); // echo '<pre>'.$txt;
				webappkit::getkit('text_rest');
				$tree=text_rest::parse($txt);
				$formatter=Text_reST_Formatter::factory('html');
				$this->response->doc=$formatter->format($tree);
				// echo '<pre>'; print_r($doc);
			} else $this->response->doc=null;*/

            // getting subkits configs

		} catch (WakException $e) {
			print_r($e);
		}
    }

	/**
	* an invalid kit page
	*/
	public function badkit() {
        return true;
	}

    function badphp() {

    }

    function tests() {
        return $this->_runKitTests($this->response->kit);
    }

    /**
     * executes a kit's embedded unit tests
     * @param Webappkit $kit
     */
    protected function _runKitTests(& $kit) {
		$report=$kit->tests->run();
		$this->response->tests=$report;
		$this->response->view='kit.tests';
		return true;
	}
}
